package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.OrderQueryPageBean;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Order;
import cn.itcast.service.OrderService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/order")
@CrossOrigin
public class OrderController {
    @Reference
    private OrderService orderService;

    @GetMapping("/findPage")
    public Result findPage(OrderQueryPageBean orderQueryPageBean) {
        PageResult pageResult = orderService.findPage(orderQueryPageBean);
        if (StringUtils.isEmpty(pageResult)) {
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
        return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, pageResult);
    }

    @PostMapping("/submit")
    public Result submitOrder(@RequestBody Order order) {
        boolean result = orderService.submitOrder(order);
        if (result) {
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        }
        return new Result(false, MessageConstant.CONFIRM_ORDER_FAIL);
    }

    @PostMapping("/save")
    public Result saveOrder(@RequestBody Order order) {
        boolean result = orderService.saveOrder(order);
        if (result) {
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        }
        return new Result(false, MessageConstant.ORDERSETTING_FAIL);
    }

    @GetMapping("/{id}")
    public Result findOrderById(@PathVariable("id") String id) {
        try {
            Order order = orderService.findOrderById(id);
            if (null!=order){
                return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,order);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(true,MessageConstant.QUERY_ORDER_FAIL);
    }
    @PostMapping("/updateArrival")
    public Result updateArrival(@RequestBody Map<String,Object> map){
        try {
            boolean result = orderService.updateArrival(map.get("id").toString(),Integer.parseInt(map.get("arrival").toString()));
            if (result){
                return new Result(true,MessageConstant.EDIT_ARRIVAL_SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,MessageConstant.EDIT_ARRIVAL_FAIL);
    }
}
